package com.ty.sso.util;


import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
@Component
public class SSHConnection {
	@Value("${ssh.local_port}")
	private  int LOCAl_PORT ;//本地用来转发的端口  
	@Value("${ssh.remote_port}")
	private int REMOTE_PORT;//远程服务器的数据库端口
	@Value("${ssh.bind_address}")
	private String Bind_Address ;//远程服务器的数据库的bindaddress
	@Value("${ssh.username}")
	private  String username; // 用户名
	@Value("${ssh.password}")
	private  String passwd; // 登录密码
	@Value("${ssh.host}")
	private  String host; //  主机IP
	@Value("${ssh.port}")
	private  int port; // 主机IP
	private JSch jsch;
	private Session session;
	public static void main(String[] args) throws Exception {

		SSHConnection demo = new SSHConnection();
		File file=new File("classpath:/Mysql.pem");
//		File file2=new File(demo.keyFile);
		System.out.println(file.exists());
//		System.out.println(file2.exists());
//		demo.ssh();
//		demo.sql();
	}
	

	/**
	 * 连接到指定的IP
	 * @return 
	 * 
	 * @throws JSchException
	 */
	public void ssh() throws JSchException {
		jsch = new JSch();
		session = jsch.getSession(username, host, port);
		session.setPassword(passwd);
		java.util.Properties config = new java.util.Properties();
		config.put("StrictHostKeyChecking", "no");
		session.setConfig(config);
		session.connect();
		System.out.println("connect success！");
        System.out.println(session.getServerVersion());//这里打印SSH服务器版本信息  
		session.setPortForwardingL(LOCAl_PORT, Bind_Address, REMOTE_PORT); 
		
	}
	/**
	 * 执行相关的命令
	 */
	 public  void sql() {  
	        Connection conn = null;  
	        ResultSet rs = null;  
	        Statement st = null;  
	        try {  
	            Class.forName("com.mysql.jdbc.Driver");  
	            conn = DriverManager.getConnection("jdbc:mysql://localhost:"+LOCAl_PORT+"/sso", "root", "430524");  
	            st = conn.createStatement();  
	            String sql = "SELECT COUNT(1) FROM user";  
	            rs = st.executeQuery(sql);  
	            while (rs.next())  
	                System.out.println(rs.getString(1));  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        } finally {  
	            //rs.close();st.close();conn.close();  
	        }  
	    }  
	
	
	/**
	 * 关闭
	 */
	public void closeSSH ()
	{
	    session.disconnect();
	}
}
